import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    ScrollView,
    StatusBar,
    Linking,
    ActivityIndicator,
    DeviceEventEmitter,
    TextInput,
    Alert
} from 'react-native';

import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Constant from '../../utils/Constant'//全局变量
import Header from "../../components/header";
import { ToastToUser } from '../../utils/CustomToast';
import Loading from "../../utils/Loading";

import NoData from '../../utils/NoData'

let navigation = null;

const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;


export default class SignSettingsPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            authorizeList: [],
            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1
        }
    }

    componentWillUnmount() {

    }

    componentDidMount() {
        this.refreshData()
    }




    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'签署设置'} />
                {/* 授权管理 */}
                <TouchableOpacity
                    activeOpacity={0.6}
                    onPress={() => {
                        this.addAuthorize()
                    }}>
                    <View style={styles.authorizeManagerContainer}>
                        <Text style={styles.authorizeTitle}>授权管理</Text>
                        <Text style={styles.addauthorizeTitle}>添加授权</Text>
                        <Image source={require('source/image/electron/authoniceadd.png')} style={styles.authoniceadd} />
                    </View>
                </TouchableOpacity>
                <View style={{ height: 10 }}></View>
                {this.renderList()}
                {/* 添加授权 */}
                <TouchableOpacity
                    style={{ bottom: 30, position: 'absolute' }}
                    activeOpacity={0.6}
                    onPress={() => {
                        this.addAuthorize()
                    }}>
                    <View style={styles.addauthorizeLayout}>
                        <Text style={styles.addTitle}>添加授权</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }


    renderList() {
        return (
            <View style={{ flex: 1, marginBottom: 80 }}>
                <FlatList
                    data={this.state.authorizeList}
                    renderItem={this.renderItemView.bind(this)}
                    extraData={this.state}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.2}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                />

                <Loading onRef={(ref) => (this.Loading = ref)} />
            </View>
        )
    }

    renderItemView({ item, index }) {

        return (
            <TouchableOpacity key={index} activeOpacity={1}
                onPress={() => {
                    this.chooseItem(item)
                }}>

                <View style={styles.authorizeItemContainer} key={index}>

                    <View style={{ flex: 1,marginRight:10,marginBottom:15 }}>
                        {/* 公司名称 */}
                        <View style={{ flexDirection: 'row',width:'100%',marginTop: 16 }}>
                            <Text style={styles.companyName}>{item.orgName}</Text>

                            <Text style={{fontWeight: '400', fontSize: 14, color: '#ff6600' }}>{item.isSystemTransactionAccount == 1 ? '默认' : ''}</Text>
                        </View>

                        {/* 经办人 */}
                        <Text style={styles.handlerbyperson}>经办人：{item.psnMobile}</Text>
                        {/* 授权状态 */}
                        <View style={item.authorizedStatus == 1 ? styles.statusContainer1 : styles.statusContainer}>
                            <Text style={item.authorizedStatus == 1 ? styles.status1 : styles.status}>{this.getstatus(item)}</Text>
                        </View>

                    </View>

                    {/* 设为默认 */}

                    {
                        item.authorizedStatus == 1
                            ?
                            <View style={{
                                marginRight:10
                            }}>
                                {item.isSystemTransactionAccount == 1 ? 
                                null 
                                :
                                    <TouchableOpacity style={styles.cancelContainer} onPress={() => {
                                        this.cancelAuthorize(item)
                                    }}>
                                        <Text style={styles.cancelTitle}>{'设为默认'}</Text>
                                    </TouchableOpacity>
                                }
                                

                                <TouchableOpacity style={styles.cancelContainer} onPress={() => {
                                    this.showCancelEsignAuthPop(item)
                                }}>
                                    <Text style={styles.cancelTitle}>取消授权</Text>
                                </TouchableOpacity>
                            </View>

                            :
                            null
                    }
                    {
                        item.authorizedStatus == 2
                            ?
                            <View style={{
                                marginRight:10
                            }}>

                                <TouchableOpacity style={styles.cancelContainer} onPress={() => {
                                    this.showCancelEsignAuthPop(item)
                                }}>
                                    <Text style={styles.cancelTitle}>取消授权</Text>
                                </TouchableOpacity>
                            </View>

                            :
                            null
                    }
                    {
                        index != this.state.authorizeList.length - 1
                            ?
                            <View style={styles.borderBottom} >
                            </View>
                            :
                            null
                    }


                </View>

            </TouchableOpacity>
        )
    }

    getstatus(item) {
        if (item.authorizedStatus == 0) {
            return '过期失效'
        } else if (item.authorizedStatus == 1) {
            return '已授权'
        } else if (item.authorizedStatus == 2) {
            return '等待授权'
        } else if (item.authorizedStatus == 3) {
            return '审批未通过'
        } else if (item.authorizedStatus == 4) {
            return '已取消授权'
        } else {
            return '未确认'
        }
    }

    refreshData = () => {
        this.setState({
            isRefresh: true,
            pageNo: 1,
            authorizeList: []
        }, function () {
            this.getAuthorizeLists()
        })
    }

    getAuthorizeLists() {

        let param = {
            pageNo: this.state.pageNo,
            pageSize: 20,
            merchantId: Constant.userInfo.merchantId,
            authorizedStatus: [1, 2]
        }

        HttpUtils.postRequest(HttpUrls.merchantAuthList, param)
            .then((result) => {
                console.log('====>>>>>>>>>')
                console.log(result)
                let data = result.data
                if (data) {
                    let resultList = data.resultList

                    if (resultList && resultList != null && resultList.length > 0) {

                        this.setState({
                            authorizeList: this.state.authorizeList.concat(resultList),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: resultList.length >= 20 ? 0 : 1,
                            })

                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch((error) => {

            });
    }


    renderEmpty() {
        if (!this.state.isRefresh) {
            return (
                <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />
            )
        } else {
            return (
                null
            )
        }
    }

    renderFooter() {
        if (this.state.showFoot === 1) {
            return <View style={{height: Constant.bottomHeight}}/>;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }



    _onEndReached() {
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return null;
        }

        //底部显示正在加载更多数据
        this.setState(
            {
                showFoot: 2,
                pageNo: this.state.pageNo + 1
            }, function () {
                this.getAuthorizeLists()
            });


    }


    chooseItem(vin) {
        // if (this.Loading) {
        //     this.Loading.show();
        // }
    }

    //取消授权弹框
    cancelAuthorize(item) {
        // Alert.alert(
        //     '取消授权',
        //     '取消授权后，该企业认证将会删除，企业关联的模版也将会全部失效，是否确定取消授权？',
        //     [
        //         { text: '取消', onPress: () => { } },
        //         {
        //             text: '确认', onPress: () => {
        //                this.confirmCancelAuthorize(item)
        //             }
        //         },
        //     ]
        // )
        this.confirmCancelAuthorize(item)
    }

    //取消授权
    confirmCancelAuthorize(item) {

        let param = {
            id: item.id,
            isSystemTransactionAccount: item.isSystemTransactionAccount == 1 ? '0' : '1'
        }
        HttpUtils.postRequest(HttpUrls.setSystemTransactionAccount, param)
            .then((result) => {
                let data = result.data
                if (data) {
                    ///重新请求列表
                    this.refreshData()
                }
            }
            )
    }

    showCancelEsignAuthPop(item) {
        Alert.alert(
            '取消授权',
            '取消授权后，该企业认证将会删除，企业关联的模版也将会全部失效，是否确定取消授权？',
            [
                { text: '取消', onPress: () => { } },
                {
                    text: '确认', onPress: () => {
                        this.cancelEsignAuth(item)
                    }
                },
            ]
        )

    }

    cancelEsignAuth(item) {

        let param = {
            id: item.id
        }
        HttpUtils.postRequest(HttpUrls.cancelEsignAuth, param)
            .then((result) => {
                let data = result.data
                if (data) {
                    ///重新请求列表
                    this.refreshData()
                }
            }
            )
    }

    //添加授权
    addAuthorize() {
        navigation.navigate('AddAuthorizePage')
    }

}

const styles = StyleSheet.create({

    container: {
        width: screenW,
        flex: 1,
        backgroundColor: '#f6f6f6'
    },

    authorizeManagerContainer: {
        marginTop: 16,
        marginLeft: 16,
        marginRight: 16,
        height: 48,
        width: screenW - 32,
        backgroundColor: '#ffffff',
        alignItems: 'center',
        flexDirection: 'row',
        borderRadius: 6,
    },

    authorizeTitle: {
        marginLeft: 12,
        fontWeight: '400',
        fontSize: 16,
        color: '#333333'
    },

    addauthorizeTitle: {
        fontWeight: '400',
        fontSize: 16,
        color: '#333333',
        position: 'absolute',
        right: 42,
        fontWeight: '400',
        fontSize: 14,
        color: '#666666',

    },

    authoniceadd: {
        width: 24,
        height: 24,
        position: 'absolute',
        right: 12,
    },

    authorizeItemContainer: {
        // height: 100,
        marginLeft: 16,
        marginRight: 16,
        width: screenW - 32,
        backgroundColor: '#ffffff',
        // position: 'relative',
        flexDirection: 'row',
        alignItems: 'center',
    },

    companyName: {
        fontWeight: '400',
        fontSize: 16,
        color: '#333333',
        flex:1,
        marginLeft: 12
    },

    handlerbyperson: {
        fontWeight: '400',
        fontSize: 14,
        color: '#999999',
        marginTop: 6,
        marginLeft: 12
    },

    statusContainer: {
        backgroundColor: 'rgba(249,152,2,0.1)',
        width: 42,
        height: 16,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 1,
        marginTop: 6,
        marginLeft: 12
    },

    statusContainer1: {
        backgroundColor: 'rgba(110,204,73,0.1)',
        width: 42,
        height: 16,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 1,
        marginTop: 6,
        marginLeft: 12
    },

    status: {
        fontWeight: '500',
        fontSize: 8,
        color: '#F99802',
    },

    status1: {
        fontWeight: '500',
        fontSize: 8,
        color: '#2CE454',
    },


    cancelContainer: {
        width: 72,
        height: 28,

        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 3,
        borderColor: '#E5E5E5',
        borderWidth: 0.8,
        marginTop: 10
    },

    cancelTitle: {
        fontWeight: '400',
        fontSize: 12,
        color: '#333333',
    },

    borderBottom: {
        borderBottomColor: '#E4E4E4',
        borderBottomWidth: 1,
        marginLeft: 12,
        marginRight: 12,
        position: 'absolute',
        bottom: 0,
        width: screenW - 32 - 24,
    },



    addauthorizeLayout: {
        marginLeft: 15,
        marginRight: 15,
        width: screenW - 30,
        height: 46,
        backgroundColor: '#FFE000',
        borderRadius: 4,
        alignItems: 'center',
        justifyContent: 'center',
    },

    addTitle: {
        fontWeight: '500',
        fontSize: 15,
        color: '#222222',
    }


})